<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :on-preview="preview"
      :file-list="fileList"
      :class="{ disabled: fileComputed }"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width: 180px"
    ></el-progress>
    <el-dialog :visible.sync="showDialog" title="图片预览">
      <img :src="imgUrl" alt="" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
var cos = new Cos({
  SecretId: 'AKIDlLiqjNlvrXy94lCNJzPaVBcnlVzEDxSh', // 身份识别 ID
  SecretKey: '2oKaaLq55pLbcNuCF2ZrtgDUWIp8C0Yr' // 身份密钥
})
export default {
  data () {
    return {
      currentFileUid: '', // 记录当前上传图片的uid
      fileList: [],
      showDialog: false,
      imgUrl: '',
      percent: 0,
      showPercent: false
    }
  },

  computed: {
    fileComputed () {
      return this.fileList.length === 1
    }
  },

  methods: {
    // 覆盖默认的上传行为
    upload (params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'photo-1313051656', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          // console.log(data)
          if (!err && data.statusCode === 200) {
            // 获取成功的返回地址
            // fileList才能显示到上传到组件上，此时替换url地址
            // 需要知道当前上传成功的是哪一张图片
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true } // upload为True表示上传完毕，这个属性为我们后期应用的时候做标记
              }
              return item
            })
            this.percent = 0
            this.showPercent = 0
          }
        })
      }
    },

    // 上传文件前的钩子
    beforeUpload (file) {
      // 检查哈文件大小
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.some(item => item === file.type)) {
        this.$message.error('上传图片只能是JPG、GIF、BMP、PNG格式')
        return false
      }
      // 检查文件大小，限制5M   1M = 1024kb  1kb = 1024b
      const maxsize = 5 * 1024 * 1024
      if (file.size > maxsize) {
        this.$message.error('上传图片大小不能超过5M')
        return false
      }
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },

    // 上传文件的钩子
    changeFile (file, fileList) {
      this.fileList = fileList.map(item => item)
    },

    // 文件移除时的钩子
    handleRemove (file, fileList) {
      // console.log(file)
      // console.log(fileList)
      // 需上传到云端才能成功
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },

    preview (file) {
      this.imgUrl = file.url
      this.showDialog = true
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
